package com.ziyucoding.springboot.labs.lab11.netty.demo1;

import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端
 *
 * @author ziyucoding
 * @date 2022-11-09
 **/
public class Client {
    /**
     * HOST
     */
    private static final String HOST = "127.0.0.1";

    /**
     * 端口
     */
    private static final int PORT = 8899;

    /**
     * 休眠时间（单位：毫秒）
     */
    private static final int SLEEP_TIME = 3000;

    public static void main(String[] args) throws IOException {
        final Socket socket = new Socket(HOST, PORT);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("客户端启动成功");

                while (true) {
                    try {
                        String msg = "hello, netty";
                        System.out.println("客户端发送数据：" + msg);
                        socket.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
                    } catch (IOException e) {
                        System.out.println("客户端发送数据异常");
                        e.printStackTrace();
                    }

                    // 休眠
                    sleep();
                }
            }
        }).start();

    }

    /**
     * 休眠
     *
     * @return void
     **/
    private static void sleep() {
        try {
            Thread.sleep(SLEEP_TIME);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
